package test.enba.es.service;

import com.enba.boot.es.manager.ElasticsearchPageHelper;
import java.util.List;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import test.enba.es.doc.Product;
import test.enba.es.repository.ProductRepository;

@Service
public class ProductService {

  @Autowired private ProductRepository productRepository;

  private final ElasticsearchPageHelper<Product> elasticsearchPageHelper;

  public ProductService(ElasticsearchPageHelper<Product> elasticsearchPageHelper) {
    this.elasticsearchPageHelper = elasticsearchPageHelper;
  }

  // 保存产品
  public Product saveProduct(Product product) {
    return productRepository.save(product);
  }

  // 根据 ID 查找产品
  public Product findProductById(String id) {
    return productRepository.findById(id).orElse(null);
  }

  // 根据名称查找产品
  public List<Product> findProductsByName(String name) {
    return productRepository.findByName(name);
  }

  // 根据价格范围查找产品
  public List<Product> findProductsByPriceRange(double minPrice, double maxPrice) {
    return productRepository.findByPriceBetween(minPrice, maxPrice);
  }

  // 删除产品
  public void deleteProduct(String id) {
    productRepository.deleteById(id);
  }

  /**
   * 分页查询产品
   *
   * @param name 产品名称
   * @param page 当前页码
   * @param size 每页大小
   * @return 分页结果
   */
  public Page<Product> searchProductsByName(String name, int page, int size) {
    // 构建查询条件
    NativeSearchQuery query =
        new NativeSearchQueryBuilder().withQuery(QueryBuilders.matchQuery("name", name)).build();

    // 构建分页请求
    Pageable pageable = elasticsearchPageHelper.buildPageRequest(page, size);

    // 执行分页查询
    return elasticsearchPageHelper.search(query, pageable, Product.class);
  }
}
